# -*- coding: utf-8 -*-

"""
# @Time    : 2022/7/20 0020 10:29
# @Author  : Silva
# @File    : db_mysql.py
"""

'''
原生pymysql操作简单封装
'''

import pymysql


class SQLHelper():

    def __init__(self, host='', port='', user='', password='', database='', charset='utf-8'):

        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        self.charset = charset
        self.init_db()

    def init_db(self):
        self.db_connection = pymysql.connect(host=self.host,
                                             port=self.port,
                                             user=self.user,
                                             password=self.password,
                                             db=self.database,
                                             charset=self.charset)
        self.cursor = self.db_connection.cursor(cursor=pymysql.cursors.DictCursor)

    def find_all(self, sql):
        self.ping()
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    def find_one(self, sql):
        self.ping()
        self.cursor.execute(sql)
        return self.cursor.fetchone()

    def insert_data(self, sql, value=None):
        self.ping()
        if value:
            msg = self.cursor.executemany(sql, value)
        else:
            msg = self.cursor.execute(sql, value)
        self.db_connection.commit()
        return msg

    def update_one(self, sql):
        self.ping()
        msg = self.cursor.execute(sql)
        self.db_connection.commit()
        return msg

    def delete(self, sql):
        self.ping()
        msg = self.cursor.execute(sql)
        self.db_connection.commit()
        return msg

    def ping(self):
        try:
            self.db_connection.ping()
        except:
            self.init_db()

    def __del__(self):
        self.db_connection.close()
